package me.zhengjie.exercise.controller;

import io.swagger.annotations.ApiOperation;
import me.zhengjie.annotation.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exercise.entity.ExerciseUser;
import me.zhengjie.exercise.service.ExerciseUserService;
import me.zhengjie.exercise.vo.ExerciseUserSearchVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * @author wanggang
 */
@RestController
@RequestMapping("/api/user")
public class ExerciseUserController {
    @Autowired
    private ExerciseUserService userService;

    private static final String ENTITY_NAME = "user";

    @GetMapping("/test")
    public ResponseEntity<String> queryTest() {
        List<ExerciseUser> list = userService.searchJpaTest();
        System.out.println(list);
        return new ResponseEntity<>("test controller api!", HttpStatus.OK);
    }

    @ApiOperation("查找用户")
    @GetMapping(value = "/{id}")
    public ResponseEntity<Object> findOne(@PathVariable String id) {
        return new ResponseEntity<>(userService.findOne(Long.valueOf(id)), HttpStatus.OK);
    }

    @ApiOperation("查询用户")
    @GetMapping(value = "/all")
    public ResponseEntity<Object> queryAll(ExerciseUserSearchVO resources) {
        return new ResponseEntity<>(userService.queryAll(resources), HttpStatus.OK);
    }

    @ApiOperation("查询用户")
    @GetMapping
    public ResponseEntity<Object> query(ExerciseUserSearchVO resources, Pageable pageable) {
        return new ResponseEntity<>(userService.queryAll(resources, pageable), HttpStatus.OK);
    }

    @Log("新增用户")
    @ApiOperation("新增用户")
    @PostMapping
    public ResponseEntity<Object> create(@Validated @RequestBody ExerciseUser resources) {
        if (resources.getId() != null) {
            throw new BadRequestException("A new " + ENTITY_NAME + " cannot already have an ID");
        }
        ExerciseUser user = userService.create(resources);
        return new ResponseEntity<>(user, HttpStatus.OK);
    }

    @Log("修改用户")
    @ApiOperation("修改用户")
    @PutMapping
    public ResponseEntity<Object> update(@Validated(ExerciseUser.Update.class) @RequestBody ExerciseUser resources) {
        ExerciseUser user = userService.update(resources);
        return new ResponseEntity<>(user, HttpStatus.OK);
    }

    @Log("删除用户")
    @ApiOperation("删除用户")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Set<Long> ids) {
        userService.delete(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
